<?php

    class Pages extends ActiveRecord {
        var $template_dir;
        
        function Pages()
        {
            $conf = array('table'=>DB_PREFIX.'pages');
            $this->ActiveRecord($conf);
            $this->template_dir = VIEWS.'/admin/pages/templates';
            $this->protected_fields('user_id'); 
        }
        
        function validate()
        {
            $this->validates_presence_of('title');
        }
        
        function after_validation()
        {            
            // sanitize meta information and title
            $this->kill_xss();
            
            $index_name = $this->get('index_name');
            if ( empty($index_name) )  {
                $this->set('index_name', $this->create_index_name($this->get('title')));
            } else {
                $this->set('index_name', $this->create_index_name($index_name)); // just to make sure its unique
            }
            // check for index page
            $is_new_index = $this->get('is_index');
            if ( $is_new_index )
            {
                $this->db->Execute('UPDATE `'.$this->table.'` SET is_index=0 WHERE is_index=1'); // clear out old home page
            }
            
        }
        
        function kill_xss()
        {
            // clean out any potentially bad xss
            include_once VENDOR.'/safehtml/safehtml.php';
            $safe =& new safehtml();
            foreach(array('meta_title','meta_keywords','meta_description','title') as $field)
            {
                $content = '';
                $content = $this->get($field);
                $cleanedhtml = $safe->parse($content);
                $this->set($field,strip_tags($cleanedhtml)) ;
                $safe->clear();
            }
        }
        
        function after_validation_before_create()
        {
            $this->set('user_id',$_SESSION['user_id']);  
            $this->restrict_permissions = $this->get('restrict_permissions');
        }
        
        function after_validation_on_update()
        {
            # need to update URL, title/meta title in the search_index
            use_model('search_index');
            $index = new Search_Index();
            if ( $index->load($this->get('search_index_id')) )
            {
                $index->set('url','/content/'.$this->get('index_name'));
                if ( $title = $this->get('meta_title') )
                {
                    $index->set('title',$title);
                } else {
                    $index->set('title',$this->get('title'));
                }
                $index->save();
            }  else { // no search index yet so create one for it
                $index->set('url', get_installed_path().'/content/'.$this->get('index_name'));
                if ( $title = $this->get('meta_title') )
                {
                    $index->set('title',$title);
                } else {
                    $index->set('title',$this->get('title'));
                }
                $index->save();
                $this->set('search_index_id',$index->get('id'));
                $this->save();
            }          
        }
        
        function after_validation_on_create()
        {                     
            if ( $this->restrict_permissions )
            {
                $this->page_permissions($this->get('id'),array($this->get('user_id')));
                unset($this->restrict_permissions);
            }
            
            # create new entry in the search_index table, put in url and write the search_index_id to this row
            use_model('search_index');
            $index = new Search_Index();
            $index->set('url', get_installed_path().'/content/'.$this->get('index_name'));
            if ( $title = $this->get('meta_title') )
            {
                $index->set('title',$title);
            } else {
                $index->set('title',$this->get('title'));
            }
            $index->save();
            $this->set('search_index_id',$index->get('id'));
            $this->save();
        }
        
        // returns index_name of page that is marked as index
        function get_index_page()
        {
            $page = $this->find( array(
                                        'search'=>'first',
                                        'conditions'=>'is_index=1',
                                        'fields'=>'index_name'
                                        )
                                );
            return $page['index_name'];
        }
        
        // loads page based on index name or returns false
        function load_page($index_name)
        {
            $page = $this->find( array(
                                        'search'=>'first',
                                        'conditions'=>array('index_name=?',$index_name),
                                        'fields'=>'id'
                                        ) 
                                );
            if ( !empty($page['id']) )
            {
                $this->load($page['id']);
            }
            if (!$this->is_loaded()) return false;
        }
        
        function get_pages_as_list()
        {
            return $this->db->GetAssoc('SELECT id, title FROM `'.$this->table.'` ORDER BY title');
        }
        
        function get_pages_for_js()
        {
            return $this->db->GetAssoc('SELECT index_name, title FROM `'.$this->table.'` ORDER BY title');
        }
        
        function before_delete()
        {
            $this->id_to_delete = $this->get('id');
            $this->parent_id_of_current = $this->get('parent_id');
            $this->saved_search_id = $this->get('search_index_id');
        }
        
        function after_delete()
        {
            // change parent nodes
            $this->db->Execute('UPDATE `'.$this->table.'` SET parent_id=? WHERE parent_id=?',
                              array($this->parent_id_of_current,
                                    $this->id_to_delete));
            
            // delete parent content
            use_model('page_content');
            $c = new Page_Content();
            $c->delete_page_content($this->id_to_delete);
            
            // delete search index
            use_model('search_index');
            $index = new Search_Index();
            if ( $index->load($this->saved_search_id) )
            {
                $index->delete();
            }
        }
        
        // returns list of templates
        function get_templates($include_snippets=false)
        {
            // read templates from system
            $folder_name = $this->template_dir;
            $folder = opendir($folder_name);
            $list = array();
            if ( $include_snippets )
            {
                $snippets_pattern = '';
            } else {
                $snippets_pattern = '/^\_/';
            }
            while ( $file = readdir($folder))
            {
                if ( $file != '.' && $file != '..' 
                     && !preg_match('/^\./',$file)
                     && !preg_match($snippets_pattern,$file)){
                    if (!is_dir( $folder_name.$file )){                                    
                        // get name of template
                        $template_data = implode('', file($folder_name.'/'.$file));
                        if ( preg_match("|Template Name:(.*)|i", $template_data, $name)){
                                $template_name =  $name[1];
                        } else {
                            $template_name = $file;
                        }
                        $list[$file] = $template_name; 
                    }
                }
            }    
            closedir( $folder) ;
            asort($list);
            return $list;
        }
        
        // returns actual code of template file
        function get_template_code($tpl)
        {
            // make tpl filename safe
            $file = $this->_template_name_to_safe($tpl);
            $path = $this->template_dir.'/'.$file;
            if ( file_exists($path) && is_readable($path) )
            {
                return file_get_contents($path);
            } else {
                return false;
            }
        }
        
        function write_to_template($post)
        {
            if ( !$this->template_is_writable($post['template_name']) ) {
                return false;
            }
            // write file to system;
            $filename = $this->_template_name_to_safe($post['template_name']);
            if ( $fh = fopen($this->template_dir.'/'.$filename,'w+'))
            {
                if ( !fwrite($fh,$post['template_code']) )
                {
                    return false;
                }
            } else {
                return false;
            }
            return true;
        }
        
        function _template_name_to_safe($tpl) 
        {
            $file = str_replace('.php','',$tpl);
            $file = strtr($file,'/\\','');
            return $file.'.php';
        }
        
        function template_is_writable($tpl)
        {
            $template = $this->_template_name_to_safe($tpl);
            return is_writable($this->template_dir.'/'.$template);
        }
        
        function pages_to_ul($parent_id=0)
        {
            static $output;
            if(empty($output)){
                $output = "<ul>\n";
            }
            $pages   = $this->db->GetAll('SELECT 
                                            id,parent_id,title,index_name
                                          FROM 
                                            `'.$this->table.'` 
                                          WHERE parent_id=?',
                                          array($parent_id));
            // do kid check
            foreach($pages as $page){
                $output.= "<li><a href='".get_installed_path()."/content/{$page['index_name']}/'>{$page['title']}</a>";
                $count = $this->db->GetOne('SELECT count(id) FROM `'.$this->table.'` WHERE parent_id=?',array($page['id']));
                if($count > 0){
                    $output .= "\n<ul>\n";
                    $this->pages_to_ul($page['id']);
                } else {
                    $output .= "</li>\n\n";   
                }
            }
            $output .= '</ul>';
            return $output;
        }
        
        function clear_page_list_cache()
        {
            require_once(VENDOR.'/cache/Lite.php');
            $options = array( 'cacheDir'=>CACHE.'/');            
            $Cache_Lite = new Cache_Lite($options);
            $Cache_Lite->remove('pages_to_ul');
            $Cache_Lite->remove('pages_to_list_options');
        }
        
        function pages_to_ul_cached($parent_id=0)
        {
            require_once(VENDOR.'/cache/Lite.php');
            $options = array( 'cacheDir'=>CACHE.'/', 'cacheLifetime'=>86400 * 14);            
            $Cache_Lite = new Cache_Lite($options);
            if ( $output = $Cache_Lite->get('pages_to_ul') )
            {
                return $output;
            } else {
                $output = $this->pages_to_ul($parent_id);
                $Cache_Lite->save($output);
                return $output;
            }
        }
        
        function pages_to_list_options_cached($parent_id=0,$level=0)
        {
            require_once(VENDOR.'/cache/Lite.php');
            $options = array( 'cacheDir'=>CACHE.'/', 'cacheLifetime'=>86400 * 14);            
            $Cache_Lite = new Cache_Lite($options);
            if ( $output = $Cache_Lite->get('pages_to_list_options') )
            {
                return $output;
            } else {
                $output = $this->pages_to_list_options($parent_id,$level);
                $Cache_Lite->save($output);
                return $output;
            }
        }
        
        function pages_to_list_options($parent_id=0,$level=0)
        {
            static $output;
            // get current page
            $pages   = $this->db->GetAll('SELECT 
                                            id,parent_id,title,index_name
                                          FROM 
                                            `'.$this->table.'` 
                                          WHERE parent_id=?',
                                          array($parent_id));
            // do kid check
            foreach($pages as $page){
                $output.= "<option value='{$page['id']}'>".
                            str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$level).
                          "{$page['title']}</option>";
                $count = $this->db->GetOne('SELECT count(id) FROM `'.$this->table.'` WHERE parent_id=?',array($page['id']));
                if($count > 0){
                    $this->pages_to_list_options($page['id'],$level+1);
                }
            }
            return $output;
        }
        
        function get_page_users($page_id)
        {
            return $this->db->GetAssoc("SELECT 
                                          u.id, concat(u.first_name,' ',u.last_name) 
                                        FROM
                                          `".DB_PREFIX."pages_users` p, 
                                          `".DB_PREFIX."users` u
                                        WHERE
                                         p.page_id =?
                                        AND
                                         u.id = p.user_id",array($page_id));
        }
        
        function page_permissions($page_id,$users=array())
        {
            if ( $page_id > 0 )
            {
                $this->db->Execute('DELETE FROM `'.DB_PREFIX.'pages_users` WHERE page_id=?',array($page_id));
                $this->db->Execute('UPDATE `'.$this->table.'` SET has_permissions=0 WHERE id=?',array($page_id));
                if ( count($users) > 0 )
                {
                    foreach( $users as $user )
                    {
                        $this->db->Execute('INSERT INTO `'.DB_PREFIX.'pages_users` (page_id,user_id) values (?,?)',
                                            array($page_id,$user));
                    }
                    // update the 
                    $this->db->Execute('UPDATE '.$this->table.' SET has_permissions=1 WHERE id=?',array($page_id));
                }
                return true;
            } else {
                return false;
            }
        }
        
        function update_search_index_with_content()
        {
            if ( !$this->is_loaded()) return;
            use_model('search_index');
            $index = new Search_Index();
            if ( $index->load($this->get('search_index_id')) )
            {
                // get all content 
                $content = '';
                $rs      = $this->db->Execute('SELECT content FROM `'.DB_PREFIX.'page_content` WHERE page_id=?',array($this->get('id')));
                while ( !$rs->EOF )
                {
                    $content .= $rs->fields['content'];
                    $rs->MoveNext();
                }
                $index->set('content',$index->prepare_content_for_search_index($content));
                $index->save();
            }
        }
        
    }

?>